const PhoneDatas = appRequire('model/desktop/PhoneDatas');
const PageResultVo = appRequire('vo/PageResultVo.js');
class PhoneDatasSequelizeDao {
  constructor() {

  }
  static async create() {
    await PhoneDatas.sync();
  }
  static async saveOne(phoneDatas) {
    phoneDatas.id=0;
    try {
      await PhoneDatas.create(phoneDatas);
    } catch (error) {
      throw new Error(error);
    }
  }
  static async saveMany(phoneDatasList) {
    phoneDatas.id=0;
    try {
      await PhoneDatas.bulkCreate(phoneDatasList);
    } catch (error) {
      throw new Error(error);
    }
  }

  static async updateOne(phoneDatas) {
    try {
      await PhoneDatas.update(phoneDatas,{where:{id:phoneDatas.id}});
    } catch (error) {
      throw new Error(error);
    } 
  }
  static async deleteById(id) {
    try {
      await PhoneDatas.destroy({where:{id}});
    } catch (error) {
      throw new Error(error);
    }
  }
  static async deleteMany(ids) {
    try {
      ids = ids.split(",");
      console.log(ids);
      await PhoneDatas.destroy({where:{id:ids}});
    } catch (error) {
      throw new Error(error);
    }
  }
  /**
   * 定制化查找字段
   * @param {*} id 
   */
  static async findOne(id) {
    try {
      let data = await PhoneDatas.findOne({
        where:{
          id
        },
        raw:true,
        attributes: { exclude: [] },
      });
      return data;
    } catch (error) {
      throw new Error(error);
    } 
  }
  static async findById(id) {
    try {
      let data = await PhoneDatas.findOne({
        where:{
          id
        },
        raw:true,
        attributes: { exclude: [] },
      });
      return data;
    } catch (error) {
      throw new Error(error);
    } 
  }
  static async findAll() {
    try {
      let data = await PhoneDatas.findAll({
        raw:true,
        attributes: { exclude: [] },
      });
      return data;
    } catch (error) {
      throw new Error(error);
    } 
  }
  static async findByPage(page) {
    try {
      let offset = (page.pageNum-1)*page.pageSize;
      let limit = page.pageSize;
      let where = {};
      //动态拼装sql的where条件
      if(page.searchParams){
        if(page.searchParams.username){
          where.username = {
            [Op.like]: `%${page.searchParams.username}%`,
          }
        }
        if(page.searchParams.firstLvDept){
          where.first_lv_dept = {
            [Op.like]: `%${page.searchParams.firstLvDept}%`,
          }
        }
        if(page.searchParams.secondLvDept){
          where.second_lv_dept = {
            [Op.like]: `%${page.searchParams.secondLvDept}%`,
          }
        }
      }
      let result = await PhoneDatas.findAndCountAll({
        where,offset,limit,raw:true,attributes:{exclude:[]},order:[["id","DESC"]]
      })
      console.log(result)
       return PageResultVo.success('success',result.count,result.rows);
    } catch (error) {
      throw new Error(error);
    } 
  } 
}
module.exports = PhoneDatasSequelizeDao;